<template>
    <van-list class="comment-list"
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <comment-item
      @reply-click="$emit('reply-click', $event)"
      v-for="(item) in list" :key="item.com_id" :comment="item"
      ></comment-item>
    </van-list>
</template>

<script>
import { getCommentsAPI } from '../../../api/index.js'
import CommentItem from './comment-item.vue'
export default {
  name: 'CommentList',
  components: {
    CommentItem
  },
  props: {
    sourceId: { // 源id,文章id评论id
      type: String,
      default: ''
    },
    type: { // 设置默认状态为a,表示父组件不穿该值时,默认为文章评论列表查询
      type: String,
      default: 'a'
    }
  },
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      offset: null // 翻页便宜量,如果有id,则根据id找后续的列表数据
    }
  },
  methods: {
    unshiftComment (res) {
      this.list.unshift(res)
    },
    async onLoad () {
      try {
        // 1. 根据获取数据接口
        const res = await getCommentsAPI({
          type: this.type,
          source: this.sourceId,
          offset: this.offset,
          limit: 3
        })
        // console.log(res)
        // 2. 将返回的数据拼接到数组的最后面
        this.list.push(...res.data.data.results)

        this.$emit('onload-success', res.data.data.total_count)
        // 3. 将加载更多loiading 设置为false
        this.loading = false

        // 4. 判断有无后续数据,如果有则更新offset,如果没有则将finished改为true
        if (res.data.data.results.length === 0) {
          this.finished = true
        } else {
          this.offset = res.data.data.last_id
        }
      } catch (error) {
        console.log(error)
        this.loading = false
      }
    }
  }
}
</script>

<style lang="less" scoped>

</style>
